package com.learn.ProducerConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用JUC让指定方法顺序执行，指定唤醒
 * Condition  可以对同一个lock对象多次实现
 * 从而通过await + signal唤醒不同对象 进行排序监控
 */
public class LockConditionPc {
    public static void main(String[] args) {
        Way3 way = new Way3();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                way.one();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                way.two();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                way.three();
            }
        },"C").start();
    }
}
class Way3{
    public int num=1;
    Lock lock = new ReentrantLock();
    //同步监视器
    Condition con1 = lock.newCondition();
    Condition con2 = lock.newCondition();
    Condition con3 = lock.newCondition();

    public void one(){
        lock.lock();
        try {
            while(num!=1) {
                con1.await();
            }
            num=2;
            con2.signal();
            System.out.println(Thread.currentThread().getName()+"AAAAAAA");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void two(){
        lock.lock();
        try {
            while(num!=2) {
                con2.await();
            }
            num=3;
            con3.signal();
            System.out.println(Thread.currentThread().getName()+"BBBBBBB");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void three(){
        lock.lock();
        try {
            while(num!=3){
                con3.await();
            }
            num = 1;
            con1.signal();
            System.out.println(Thread.currentThread().getName()+"CCCCCCC");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}